<template>
	<div id="map">
		<div id="header">

			<div id="r-result" style="position: relative;">
				<div class="div_input" style="display: inline;">
					<span>出发地:</span><input type="search" id="suggestId1" size="20" style="width:150px;" v-model="searchText1" />
					<button @click="dingwei()" id="dingwei">
						<img src="../assets/dingwei.png" class="dingwei-img">
					</button>
				</div>

				<div class="div_input">
					<span>目的地:</span><input type="search" id="suggestId" size="20" value="" style="width:150px;" v-model="searchText" />
				</div>
				<mt-button type="primary" id='daohang' ref='daohang' value="导航" style="position: absolute;float:right;right: 0;"
				 @click="run(1)" v-if = "!this.flag" >导航</mt-button>
				 <mt-button type="primary" id='quxiao' ref='quxiao' value="取消" style="position: absolute;float:right;right: 0;"
				  @click="run(2)" v-else>取消</mt-button>

			</div>
			<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>

		</div>
		<div class="div_map">
			<div id="allmap" ref="allmap"></div>

		</div>

	</div>
</template>

<script>
	import BMap from 'BMap'


	export default {
		name: 'App',

		data() {
			return {
				searchText: '', //目的地
				searchText1: '', //出发地
				frist: true,
				searchReuslt: '',
				nowLoction: '',
				lushu: '',
				mycaiId: '',
				arrPois: [],
				flag:false,  //是否正在导航
				infoFlag:false,//车辆信息是否显示				
				dingweiLoc:'',//定位的地点
			}

		},

		watch: {
			arrPois() {
				console.log('daohang')
				this.daohang();

			},
			searchText(val1,val2) {
				if(val1 == ''){
					this.arrPois.splice(1, 1);
				}
				this.search('suggestId', 0)
			},
			searchText1(val) {
				if(this.dingweiLoc == val ){
					return;
				}
				if(val == ''){
					this.arrPois.splice(0, 1);
				}
					
				this.search('suggestId1', 1)
			}
		},
		beforeCreate() {
			let Screenwidth = window.screen.width;
		},
		methods: {
			/* 地图初始化*/
			map() {
				var map = new BMap.Map(this.$refs.allmap); // 创建Map实例
				window.map = map //将map变量存储在全局



				map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
				map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

				// 添加带有定位的导航控件
				var navigationControl = new BMap.NavigationControl({
					// 靠左上角位置
					anchor: BMAP_ANCHOR_TOP_LEFT,
					// LARGE类型
					type: BMAP_NAVIGATION_CONTROL_LARGE,
					// 启用显示定位
					enableGeolocation: true
				});
				map.addControl(navigationControl); 
				/*{
					添加定位控件
					var geolocationControl = new BMap.GeolocationControl();
					geolocationControl.addEventListener("locationSuccess", (e) => {
						// 定位成功事件
						this.nowLoction = e;
						var p0 = e.point.lng;
						var p1 = e.point.lat;
						// var checksum = makerArry[i].checksum;
						var point = new BMap.Point(p0, p1); //118.230272,33.482474

						this.arrPois.splice(0, 1, point);

						var address = '';
						address += e.addressComponent.province;
						address += e.addressComponent.city;
						address += e.addressComponent.district;
						address += e.addressComponent.street;
						address += e.addressComponent.streetNumber;
						this.searchText1 = address;

					});
					geolocationControl.addEventListener("locationError", function(e) {
						// 定位失败事件
						alert(e.message);
					});
					map.addControl(geolocationControl);
				}*/

				this.dingwei();

			},


			/* 导航小车动*/
			run(val) {
				if(val == 1){
					if (this.lushu) {
						let _that = this 
						if(this.flag){	
							
							console.log(this.nowLoction.lat+'-----'+this.nowLoction.lng)
						}else{
							this.lushu.start();
							this.flag = true;
							var i = document.getElementsByTagName('span');
							
							for (var y of i) {
								if (y.className == 'BMap_Marker BMap_noprint') {
									y.addEventListener('click', () => {
										if (this.infoFlag == false) {
											this.lushu.showInfoWindow()
										} else {
											this.lushu.hideInfoWindow()
										}
										this.infoFlag = !this.infoFlag;
							
									})
								}
							}
						}
						
					}else{
						return
					}
				}else{
					this.arrPois.splice(0, 2);
					this.flag = false;
					this.lushu.stop();
					map.clearOverlays();	
				}
				

			},
			daohang() {

				if (this.arrPois.length != 2) {
					return;
				}
				var lushu;

				// 实例化一个驾车导航用来生成路线

				let drv = new BMap.DrivingRoute("北京", {
					onSearchComplete: (res) => {
						if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
							let plan = res.getPlan(0);
							let arrPois = [];
							for (let j = 0; j < plan.getNumRoutes(); j++) {
								let route = plan.getRoute(j);
								arrPois = arrPois.concat(route.getPath());
							}
							map.addOverlay(new BMap.Polyline(arrPois, {
								strokeColor: "green",
								strokeWeight: 5,
							}));
							map.setViewport(arrPois);

							this.lushu = new BMapLib.LuShu(map, arrPois, {
								defaultContent: `<p>车辆类型:小轿车</p><p>车牌号:粤A12345</p>`, //"从天安门到百度大厦"
								autoView: true, //是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
								icon: new BMap.Icon('http://lbsyun.baidu.com/jsdemo/img/car.png', new BMap.Size(52, 26), {
									anchor: new BMap.Size(27, 13)
								}),
								speed: 40,
								enableRotation: true, //是否设置marker随着道路的走向进行旋转
								landmarkPois: [],
							});


						}

					}
				});
	
				drv.search(this.arrPois[0], this.arrPois[1]);

				this.chongxie()

			},


			theLocation() {
				if (this.city !== '') {
					this.map() // 用城市名设置地图中心点
				}
			},
			chongxie() {
				var _that = this;
				BMapLib.LuShu.prototype._move = function(initPos, targetPos, effect) {
					var pointsArr = [initPos, targetPos]; //点数组
					var me = this,
						//当前的帧数
						currentCount = 0,
						//步长，米/秒
						timer = 10,
						step = this._opts.speed / (1000 / timer),
						//初始坐标
						init_pos = this._projection.lngLatToPoint(initPos),
						//获取结束点的(x,y)坐标
						target_pos = this._projection.lngLatToPoint(targetPos),
						//总的步长
						count = Math.round(me._getDistance(init_pos, target_pos) / step);

					this._map.addOverlay(new BMap.Polyline(pointsArr, {
						strokeColor: "red",
						strokeWeight: 6,
						strokeOpacity: 0.5
					})); // 画线 

					// 			获取当前的位置
					// 			console.log(pointsArr[0]);
					_that.nowLoction = pointsArr[0];
					//如果小于1直接移动到下一点

					if (count < 1) {
						me._moveNext(++me.i);
						return;
					}
					//两点之间匀速移动
					me._intervalFlag = setInterval(function() {
						//两点之间当前帧数大于总帧数的时候，则说明已经完成移动
						if (currentCount >= count) {
							clearInterval(me._intervalFlag);
							//移动的点已经超过总的长度
							if (me.i > me._path.length) {
								return;
							}
							//运行下一个点
							me._moveNext(++me.i);
						} else {
							currentCount++;
							var x = effect(init_pos.x, target_pos.x, currentCount, count),
								y = effect(init_pos.y, target_pos.y, currentCount, count),
								pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
							//设置marker
							if (currentCount == 1) {
								var proPos = null;
								if (me.i - 1 >= 0) {
									proPos = me._path[me.i - 1];
								}
								if (me._opts.enableRotation == true) {
									me.setRotation(proPos, initPos, targetPos);
								}
								if (me._opts.autoView) {
									if (!me._map.getBounds().containsPoint(pos)) {
										me._map.setCenter(pos);
									}
								}
							}
							//正在移动

							me._marker.setPosition(pos);
							//设置自定义overlay的位置
							me._setInfoWin(pos);

						}
					}, timer);
				}
			},
			dingwei() {
				var _that = this;
				var geolocation = new BMap.Geolocation();
				geolocation.enableSDKLocation();
				geolocation.getCurrentPosition(function(r) {

					if (this.getStatus() == BMAP_STATUS_SUCCESS) {

						var p0 = r.point.lng;
						var p1 = r.point.lat;
						// var checksum = makerArry[i].checksum;
						var point = new BMap.Point(p0, p1); //118.230272,33.482474

						_that.arrPois.splice(0, 1, point);

						var address = '';
						address += r.address.province;
						address += r.address.city;
						address += r.address.district;
						address += r.address.street;
						address += r.address.street_number;

						_that.searchText1 = address;
						_that.dingweiLoc = address;
						map.addOverlay(new BMap.Marker(r.point));
						map.centerAndZoom(r.point, 15);
					} else {
						alert('failed' + this.getStatus());
					}
				});
				this.frist = false
			},
			search(id, sure) { // sure 确定  1出发地 还是 0目的地 

				function G(id) {
					return document.getElementById(id);
				}

				var ac = new BMap.Autocomplete( //建立一个自动完成的对象
					{
						"input": id,
						"location": map,

					});

				ac.addEventListener("onhighlight", e => { //鼠标放在下拉列表上的事件

					var str = "";
					var _value = e.fromitem.value;
					var value = "";
					if (e.fromitem.index > -1) {
						value = _value.province + _value.city + _value.district + _value.street + _value.business;
					}
					str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

					value = "";
					if (e.toitem.index > -1) {
						_value = e.toitem.value;
						value = _value.province + _value.city + _value.district + _value.street + _value.business;
					}
					str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;

					if (sure == 0) { //目的地
						this.searchText = value

					} else if (sure == 1) { //出发地
						this.searchText1 = value;

					}
					G("searchResultPanel").innerHTML = str;
				});

				var myValue;
				ac.addEventListener("onconfirm", e => { //鼠标点击下拉列表后的事件
					var _value = e.item.value;
					myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
					G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

					setPlace(this, sure);
				});

				function setPlace(_that, sure) {
					map.clearOverlays(); //清除地图上所有覆盖物
					let myGeo = new BMap.Geocoder();

					function myFun() {
						let pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
						let rs = local.getResults().getPoi(0);
						if (sure == 0) { //目的地

							_that.searchReuslt = rs;
							let p0 = rs.point.lng;
							let p1 = rs.point.lat;
							// var checksum = makerArry[i].checksum;
							let point = new BMap.Point(p0, p1); //118.230272,33.482474
							_that.arrPois.splice(1, 1, point);

						} else if (sure == 1) { //出发地
							_that.searchReuslt = rs;
							let p0 = rs.point.lng;
							let p1 = rs.point.lat;
							// var checksum = makerArry[i].checksum;
							let point = new BMap.Point(p0, p1); //118.230272,33.482474
							_that.arrPois.splice(0, 1, point);;
						}


						map.centerAndZoom(pp, 11);
						map.addOverlay(new BMap.Marker(pp)); //添加标注
					}
					let local = new BMap.LocalSearch(map, { //智能搜索
						onSearchComplete: myFun
					});
					local.search(myValue);

				}

			}


		},
		mounted() {

			this.map();

		}




	}
</script>

<style scoped lang="less">
	/* 放大缩小地图控件 */
	.BMap_stdMpZoom {
		margin-top: 50px;
	}

	/* 定位控件 */
	.BMap_noprint .anchorBL {
		margin-bottom: 10px;
	}

	#map {

		position: relative;
		width: 100%;
		height: 615 px;

		#header {
			width: 100%;
			height: 104px;
			position: fixed;
			top: 52px;/*no*/
			background-color: yellow;
			z-index: 12;


			.div_input::after {
				content: '';
				height: 0;
				display: block;
				clear: both;
				visibility: hidden;
			}

			.div_input {
				width: 80%;
				height: 52px;
				float: left;
				text-align: left;
				padding-left: 50px;
			}

			#dingwei {
				padding: 0
			}

			.dingwei-img {
				width: 16px;
				/*no*/
				height: 16px;
				/*no*/
			}
		}


		.div_map {
			width: 100%;
			height: 1126px;
			top: 104px;
			/*no*/
			position: relative;
			overflow: hidden;

			#allmap {
				position: absolute;
				/*no*/
				height: 1126px;
				top: 0;/*no*/
				width: 100%;
			}
		}

	}
</style>
